<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <!-- 警告区域 -->
      <el-alert type="warning" :closable="false" show-icon title="注意：只允许为第三级分类设置相关参数！"/>

      <!-- 选择商品分类区域 -->
      <el-row class="cat-opt">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            :options="cates"
            :props="catesProps"
            v-model="selectedCates"
            @change="catesChanged"
            clearable
          />
        </el-col>
      </el-row>

      <!-- 标签页 -->
      <el-tabs v-model="activeTab" @tab-click="tabClicked">
        <!-- 添加动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="btnDisabled" @click="addDialogVisible = true">添加参数</el-button>
          <el-table :data="manyData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染标签 -->
                <el-tag
                  v-for="(item, key) in scope.row.attr_vals"
                  :key="key"
                  closable
                  @close="tagClosed(key, scope.row)"
                >{{ item }}</el-tag>
                <!-- 新增 tag 按钮 -->
                <el-input
                  v-if="scope.row.newTagInputVisible"
                  v-model="scope.row.newTagInputValue"
                  ref="newTagInputRef"
                  size="mini"
                  @keyup.enter.native="onNewTagInputConfirm(scope.row)"
                  @blur="onNewTagInputConfirm(scope.row)"
                  class="new-tag-input"
                />
                <el-button
                  v-else
                  class="new-tag-btn"
                  size="small"
                  @click="showNewTagInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"/>
            <el-table-column label="参数名称" prop="attr_name"/>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- TODO: 修改按钮 -->
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <!-- TODO: 删除按钮 -->
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 添加静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="btnDisabled" @click="addDialogVisible = true">添加属性</el-button>
          <el-table :data="onlyData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 循环渲染标签 -->
                <el-tag
                  v-for="(item, key) in scope.row.attr_vals"
                  :key="key"
                  closable
                  @close="tagClosed(key, scope.row)"
                >{{ item }}</el-tag>
                <!-- 新增 tag 按钮 -->
                <el-input
                  v-if="scope.row.newTagInputVisible"
                  v-model="scope.row.newTagInputValue"
                  ref="newTagInputRef"
                  size="mini"
                  @keyup.enter.native="onNewTagInputConfirm(scope.row)"
                  @blur="onNewTagInputConfirm(scope.row)"
                  class="new-tag-input"
                />
                <el-button
                  v-else
                  class="new-tag-btn"
                  size="small"
                  @click="showNewTagInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index"/>
            <el-table-column label="属性名称" prop="attr_name"/>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <!-- TODO: 修改按钮 -->
                <el-button type="primary" size="mini" icon="el-icon-edit" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <!-- TODO: 删除按钮 -->
                <el-button type="danger" size="mini" icon="el-icon-delete" @click="deleteParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数/属性对话框 -->
    <el-dialog :title="'添加' + activeTabName" width="50%"
      :visible.sync="addDialogVisible"
      @close="addDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="addForm"
        ref="addFormRef"
        :rules="rules"
        label-width="70px"
      >
        <el-form-item :label="activeTabName" prop="attr_name">
          <el-input v-model="addForm.attr_name" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数/属性对话框 -->
    <el-dialog :title="'修改' + activeTabName" width="50%"
      :visible.sync="editDialogVisible"
      @close="editDialogClosed"
    >
      <!-- 内容主体 -->
      <el-form
        :model="editForm"
        ref="editFormRef"
        :rules="rules"
        label-width="70px"
      >
        <el-form-item :label="activeTabName" prop="attr_name">
          <el-input v-model="editForm.attr_name" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 分类列表
      cates: [],
      // 级联选择器配置对象
      catesProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 级联选择器数据对象: 选中的分类的 id 数组
      selectedCates: [],
      // 当前选中页签
      activeTab: 'many',
      manyData: [],
      onlyData: [],
      // 表单验证
      rules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 添加参数对话框相关设定
      addDialogVisible: false,
      addForm: { attr_name: '' },
      // 修改参数对话框相关设定
      editDialogVisible: false,
      editForm: { attr_name: '', attr_id: '' }
    }
  },
  created () {
    this.getCates()
  },
  methods: {
    // 获取分类列表
    async getCates () {
      const { data } = await this.$http.get('categories')
      if (data.meta.status !== 200) {
        return this.$message.error('获取商品分类失败，' + data.meta.msg)
      }
      this.cates = data.data
    },
    // 获取参数列表
    async getParams () {
      // 只允许选中三级分类
      if (this.selectedCates.length !== 3) {
        this.selectedCates = [] // 清空选中分类
        this.manyData = []
        this.onlyData = []
        return
      }
      // 根据所选分类 id 和当前所处的页签获取参数
      const { data } = await this.$http.get(`categories/${this.cateId}/attributes`, {params:
        { sel: this.activeTab }
      })
      if (data.meta.status !== 200) {
        return this.$message.error('获取商品参数失败，' + data.meta.msg)
      }
      // 获取成功，先处理后赋值
      data.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 独立控制新增标签输入框
        item.newTagInputValue = ''
        item.newTagInputVisible = false
      })
      if (this.activeTab === 'many') {
        this.manyData = data.data // 动态参数
      } else if (this.activeTab === 'only') {
        this.onlyData = data.data // 静态属性
      }
    },
    // 级联选择器变化回调函数
    catesChanged () {
      this.getParams()
    },
    // 页签点击事件回调
    tabClicked () {
      this.getParams()
    },
    // 添加参数对话框关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 添加参数对话框确定事件
    addParams () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeTab
        })
        if (data.meta.status !== 201) {
          return this.$message.error('添加参数失败，' + data.meta.msg)
        }
        this.addDialogVisible = false
        this.getParams()
        this.$message.success('添加参数成功')
      })
    },
    // 弹出修改参数对话框
    async showEditDialog (attrId) {
      // 查询当前参数的信息
      const { data } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, { params:
        { attr_sel: this.activeTab }
      })
      if (data.meta.status !== 200) {
        return this.$message.error('查询当前参数失败，' + data.meta.msg)
      }
      this.editForm = data.data
      this.editDialogVisible = true
    },
    // 修改参数对话框关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 修改参数对话框确定事件
    editParams () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeTab
        })
        if (data.meta.status !== 200) {
          return this.$message.error('修改参数失败，' + data.meta.msg)
        }
        this.editDialogVisible = false
        this.getParams()
        this.$message.success('修改参数成功')
      })
    },
    // 删除参数
    async deleteParams (attrId) {
      const res = await this.$confirm('是否删除该参数？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res !== 'confirm') {
        return this.$message.info('取消删除')
      }
      // 真正删除
      const { data } = await this.$http.delete(`categories/${this.cateId}/attributes/${attrId}`)
      if (data.meta.status !== 200) {
        return this.$message.error('删除参数失败，' + data.meta.msg)
      }
      this.getParams()
      this.$message.success('删除参数成功')
    },
    // 显示新增标签输入框
    showNewTagInput (item) {
      item.newTagInputVisible = true
      // 待原生 input 渲染后，自动获得焦点
      this.$nextTick(() => {
        this.$refs.newTagInputRef.$refs.input.focus()
      })
    },
    // 发起请求，保存修改后的标签
    async saveTags (item) {
      const { data } = await this.$http.put(`categories/${this.cateId}/attributes/${item.attr_id}`, {
        attr_name: item.attr_name,
        attr_sel: item.attr_sel,
        attr_vals: item.attr_vals.join(' ')
      })
      if (data.meta.status !== 200) {
        return this.$message.error('更新标签失败，' + data.meta.msg)
      }
    },
    // 新增标签确认事件
    onNewTagInputConfirm (item) {
      const val = item.newTagInputValue.trim().replace(/ /g, '')
      if (val.length > 0) {
        item.attr_vals.push(val)
        this.saveTags(item)
      }
      item.newTagInputValue = ''
      item.newTagInputVisible = false
    },
    // 删除标签
    tagClosed (key, item) {
      item.attr_vals.splice(key, 1)
      this.saveTags(item)
    }
  },
  computed: {
    // 是否禁用添加参数按钮
    btnDisabled () {
      return this.selectedCates.length !== 3
    },
    // 当前选中的三级分类 id
    cateId () {
      const len = this.selectedCates.length
      if (len === 3) {
        return this.selectedCates[len - 1]
      }
      return null
    },
    // 添加参数对话框标题
    activeTabName () {
      if (this.activeTab === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cat-opt {
  margin: 15px 0;
}
.el-tag {
  margin: 5px;
}
.new-tag-input {
  width: 120px;
}
.new-tag-button {
  transform: translateY(1.5px)
}
</style>
